package com.leyou.item.web;

import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("spec")
public class SpecController {
    @Autowired
    private SpecGroupService groupService;
    @Autowired
    private SpecParamService paramService;
    @GetMapping("/groups/of/category")
    public ResponseEntity<List<SpecGroupDTO>> queryGroupByCategory(
            @RequestParam("id") Long id){
        return ResponseEntity.ok(
                SpecGroupDTO.convertEntityList(
                        groupService.query().eq("category_id", id).list()
                )
        );
    }

    /**
     * 规格参数查询
     * @param categoryId
     * @param groupId
     * @param searching
     * @return
     */
    @GetMapping("params")
    public ResponseEntity<List<SpecParamDTO>> querySpecParams(
            @RequestParam(value = "categoryId", required = false) Long categoryId,
            @RequestParam(value = "groupId", required = false) Long groupId,
            @RequestParam(value = "searching", required = false) Boolean searching
    ){
        return ResponseEntity.ok(paramService.queryParams(categoryId, groupId, searching));
    }

    @PostMapping("group")
    public ResponseEntity<Void> saveGroup(@RequestBody SpecGroupDTO groupDTO){
        // 新增规格组
        groupService.save(groupDTO.toEntity(SpecGroup.class));
        // 返回结果
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
    @PutMapping("group")
    public ResponseEntity<Void> updateGroup(
            @RequestBody SpecGroupDTO groupDTO){
        // 更新规格组
        groupService.updateById(groupDTO.toEntity(SpecGroup.class));
        // 返回结果
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
    @PostMapping("param")
    public ResponseEntity<Void> saveParam(@RequestBody SpecParamDTO paramDTO){
        paramService.save(paramDTO.toEntity(SpecParam.class));
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }
    @PutMapping("param")
    public ResponseEntity<Void> updateParam(@RequestBody SpecParamDTO paramDTO){
        paramService.updateById(paramDTO.toEntity(SpecParam.class));
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }
    @GetMapping("/list")
    public ResponseEntity<List<SpecGroupDTO>> querySpecList(@RequestParam("id") Long categoryId) {
        return ResponseEntity.ok(groupService.querySpecList(categoryId));
    }
}
